#!/bin/sh

RED='\E[1;31m'      # 红
GREEN='\E[1;32m'    # 绿
YELOW='\E[1;33m'    # 黄
BLUE='\E[1;34m'     # 蓝
PINK='\E[1;35m'     # 粉红
RES='\E[0m'         # 清除颜色

BETA_HOST="www@kid-dev.xqw369.com"
BETA_ROOT="/mnt/dev/server"

RELEASE_HOST="www@kid.xqw369.com"
RELEASE_ROOT="/mnt/dev/server"

if [ $# -lt 1 ]
then
    echo 请输入版本，如:publish.sh beta
    exit
fi

VERSION=$1

if [ "$VERSION" == "release" ]
then
    read -n1 -p "确定要更新正式服[Y/N]?" answer
    case $answer in
        Y | y) echo
            echo -e ${RED}"准备更新正式服"${RES}
            HOST=$RELEASE_HOST
            ROOT=$RELEASE_ROOT
            ;;
        N | n) echo
            echo "Bye~"
            exit;;
    esac
else
    HOST=$BETA_HOST
    ROOT=$BETA_ROOT
fi

SSH="ssh $HOST -p 22"
if $SSH test -e ${ROOT}/center/logs/center.pid; then
    echo -e ${RED}中心服未停机${RES}
    exit
fi

if $SSH test -e ${ROOT}/product/logs/product.pid; then
    echo -e ${RED}产品服未停机${RES}
    exit
fi

root=$(cd "$(dirname "$0")"; pwd)/..

cd ${root}

echo -e ${GREEN}构建发布目录${RES}

mkdir -p ${root}/publish
mkdir -p publish/lualib
mkdir -p publish/service
mkdir -p publish/skynet
mkdir -p publish/bewater

cp -rf build publish
cp -rf bin publish
cp -rf skynet/lualib publish/skynet
cp -rf skynet/service publish/skynet
cp -rf bewater/lualib publish
cp -rf bewater/service publish
cp -rf lualib publish
cp -rf service publish
cp -rf center publish
cp -rf product publish
cp -rf shell publish

# 推送中心服
echo sh ${ROOT}/center/shell/run.sh center $VERSION > publish/run.sh
echo sh ${ROOT}/center/shell/kill.sh center > publish/kill.sh
chmod 775 publish/run.sh
chmod 775 publish/kill.sh

echo -e ${PINK}正在推送代码到远程服务器${RES}
$SSH mkdir -p ${ROOT}/center
rsync -rv --exclude={center/data/,product/data/} publish/* ${HOST}:${ROOT}/center/

echo -e ${PINK}正在启动远程服务器${RES}
$SSH ${ROOT}/center/run.sh
echo -e 进程号:${BLUE}`$SSH cat ${ROOT}/center/logs/center.pid`${RES}


# 推送产品服
echo sh ${ROOT}/product/shell/run.sh product $VERSION > publish/run.sh
echo sh ${ROOT}/product/shell/kill.sh product > publish/kill.sh
chmod 775 publish/run.sh
chmod 775 publish/kill.sh

echo -e ${PINK}正在推送代码到远程服务器${RES}
$SSH mkdir -p ${ROOT}/product
rsync -rv --exclude={center/data/,product/data/} publish/* ${HOST}:${ROOT}/product/

echo -e ${PINK}正在启动远程服务器${RES}
$SSH ${ROOT}/product/run.sh
echo -e 进程号:${BLUE}`$SSH cat ${ROOT}/product/logs/product.pid`${RES}


rm -rf publish

echo -e ${GREEN}${VERSION}发布完成${RES}
